package com.tanhua.server.service;

import com.tanhua.autoconfig.template.FaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.joda.time.DateTime;
import org.joda.time.Years;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class UserInfoService {

    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private FaceTemplate faceTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 完善个人信息
     *
     * @param userInfoVo
     */
    public void loginReginfo(UserInfoVo userInfoVo) {
        User loginUser = UserHolder.getUser();
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoVo, userInfo);
        userInfo.setId(loginUser.getId());
        userInfo.setAge(getAge(userInfoVo.getBirthday()));
        userInfoApi.add(userInfo);
    }

/*    @Deprecated //通过token获取登陆用户信息 (已弃用)
    private User getLoginUserByToken(String token) {
        String tokenKey = "TOKEN_" + token;
        String loginUser = redisTemplate.opsForValue().get(tokenKey);
        if(StringUtils.isEmpty(loginUser)) {
            throw new TanHuaException(ErrorResult.timeoutCodeError());
        }

        return JSON.parseObject(loginUser, User.class);
    }*/

    /**
     * 通过生日获取年龄
     *
     * @param birthday
     * @return
     */
    private int getAge(String birthday) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date bir = null;
        try {
            bir = df.parse(birthday);
        } catch (ParseException e) {
            throw new TanHuaException(ErrorResult.dateFormatCodeError());
        }
        Years years = Years.yearsBetween(new DateTime(bir), DateTime.now());
        return years.getYears();
    }


    /**
     * 首次登陆 用户上传头像
     *
     * @param headPhoto
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void uploadAvatar(MultipartFile headPhoto) {
        try {
            if (!faceTemplate.detect(headPhoto.getBytes())) {
                throw new TanHuaException(ErrorResult.faceError());
            }
            String url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

            //若不是第一次登陆 修改头像时删除oss存储的旧头像
            UserInfo user = userInfoApi.getById(UserHolder.getUserId());
            if(null != user && StringUtils.isNotEmpty(user.getAvatar())) {
                ossTemplate.delete(user.getAvatar());
            }

            UserInfo userInfo = new UserInfo();
            userInfo.setId(UserHolder.getUserId());
            userInfo.setAvatar(url);
            userInfoApi.update(userInfo);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改用户信息
     * @param userInfoVo
     */
    public void updateById(UserInfoVo userInfoVo) {
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoVo, userInfo);
        userInfo.setId(UserHolder.getUserId());
        userInfo.setAge(getAge(userInfoVo.getBirthday()));
        userInfoApi.update(userInfo);
    }

    /**
     * 通过id查询用户信息
     * @param userId
     * @return
     */
    public UserInfoVo getById(Long userId) {
        Long currentId = userId != null ? userId : UserHolder.getUserId();
        UserInfo userInfo = userInfoApi.getById(currentId);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        userInfoVo.setAge(userInfo.getAge() + "");
        return userInfoVo;
    }
}
